package com.zh.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description:
 * @ClassName LoginController
 * @date: 2021.02.24 16:45
 * @Author: zhanghang
 */
@Controller
public class LoginController {

//    @GetMapping({"/","index"})
//    public String index(){
//        return "index";
//    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    // 登录
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(String username, String password, Model model){
        //获取当前用户数据
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);//执行登录方法
            return "index";
        }catch (UnknownAccountException e){
            //用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不存在");
            return "login";
        }
    }

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,Shiro");
        return "index";
    }
    @RequestMapping("/user/add")
    @RequiresRoles("admin")
    public String add(){
        return "/user/add";
    }
    @RequestMapping("/user/update")
    @RequiresPermissions("user:add")
    public String update(){
        return "/user/update";
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }
}
